﻿using Core.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.DataContracts;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Core.Tools
{
    public static class SerializeHelper
    {
        public static void Serialize<T>(T t,string path)
        {
            DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
            try
            {
                using var writer = new XmlTextWriter(path, Encoding.UTF8);
                writer.Formatting = Formatting.Indented;
                dataContractJsonSerializer.WriteObject(writer, t);
            }
            catch (Exception ex)
            {
                ExLog.ErrorLogCore(ex.Message);
            }
        }
        public static void Deserialize<T>(string path,out T? t)
        {
            t = default(T);
            DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
            try
            {
                using XmlTextReader reader = new XmlTextReader(path);
                t = (T?)dataContractJsonSerializer.ReadObject(reader);
            }
            catch (Exception ex)
            {
                ExLog.ErrorLogCore(ex.Message);
            }
        }
    }
}

